import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

const ETHER_ADDRESS = "0x0000000000000000000000000000000000000000";

const balanceSlice = createSlice({
  name: "balance",
  initialState: {
    TokenWallet: "0", // wei转换需要用到字符串
    TokenExchange: "0",
    EtherWallet: "0",
    EtherExchange: "0",
  },
  reducers: {
    // action纯函数
    setTokenWallet(state, action) {
      console.log("11111111111111");
      state.TokenWallet = action.payload;
    },
    setTokenExchange(state, action) {
      state.TokenExchange = action.payload;
    },
    setEtherWallet(state, action) {
      state.EtherWallet = action.payload;
    },
    setEtherExchange(state, action) {
      state.EtherExchange = action.payload;
    },
  },
});

export const {
  setTokenWallet,
  setTokenExchange,
  setEtherWallet,
  setEtherExchange,
} = balanceSlice.actions;

export default balanceSlice.reducer;

/**
 * @dev 执行异步请求
 */
export const loadBalanceData = createAsyncThunk(
  "balance/fetchBalanceData",
  async (data, { dispatch }) => {
    const { web3, account, tokenContract, exchangeContract } = data;
    // 获取钱包的token
    const TokenWallet = await tokenContract.methods.balanceOf(account).call();
    dispatch(setTokenWallet(TokenWallet));
    // 获取交易所的token
    const TokenExchange = await exchangeContract.methods
      .balanceOf(tokenContract.options.address)
      .call();
    dispatch(setTokenExchange(TokenExchange));
    // 获取钱包ether
    const EtherWallet = await web3.eth.getBalance(account);
    dispatch(setEtherWallet(EtherWallet));
    // 获取交易所ether
    const EtherExchange = await exchangeContract.methods
      .balanceOf(ETHER_ADDRESS)
      .call();
    dispatch(setEtherExchange(EtherExchange));
  }
);
